package com.wno704.system.util;

import com.saxonica.xqj.SaxonXQDataSource;

import javax.xml.xquery.*;

/**
 * @ClassName XQueryUtil
 * @Description TODO
 * @Author wno704
 * @Date 2022/6/7 18:14
 * @Version 1.0
 */
public class XQueryUtil {

    private static XQDataSource ds = new SaxonXQDataSource();

    /**
     * 根据给定xpath查询节点值
     */
    public static String getNodeValue(String xml, String xpath) {
        XQConnection conn = null;
        XQExpression exp = null;
        XQSequence sequence = null;
        String nodeValue = null;

        try {
            conn = ds.getConnection();
            exp = conn.createExpression();
            exp.bindDocument(XQConstants.CONTEXT_ITEM, xml, null, null);
            sequence = exp.executeQuery("data(" + xpath + ")");
            if (sequence.next()) {
                nodeValue = sequence.getItemAsString(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return nodeValue;
    }

    /**
     * 将接口xml格式化成标准xml格式
     */
    public static String executeXquery(String context, String script) throws XQException {
        XQConnection conn = null;
        XQExpression exp = null;
        XQSequence sequence = null;
        String result = null;
        conn = ds.getConnection();
        exp = conn.createExpression();
        exp.bindDocument(XQConstants.CONTEXT_ITEM, context, null, null);
        sequence = exp.executeQuery(script);
        if (sequence.next()) {
            result = sequence.getItemAsString(null);
        }
        return result;
    }


    public static String executeXquery(String script) throws XQException {
        XQConnection conn = null;
        XQExpression exp = null;
        XQSequence sequence = null;
        String result = null;
        conn = ds.getConnection();
        exp = conn.createExpression();
        sequence = exp.executeQuery(script);
        if (sequence.next()) {
            result = sequence.getItemAsString(null);
        }
        return result;
    }

    /**
     * 取得XML文档的body部分
     */
    public static String getXMLBody(String input) {
        return input.replaceFirst("\\<\\?xml.+?\\?>", "");
    }
}
